<script setup lang="ts">
import { onMounted } from 'vue'
import { useStorage } from '@vueuse/core'
// import api from './api'
import { setToken } from '@/utils/auth/token'
import { getLocal, removeLocal, setLocal } from '@/utils/storage'
import bgImg from '@/assets/images/login_bg.png'
import { addDynamicRoutes } from '@/router'
import { getCaptcha } from '@/api/code'
import type { UserLoginSendModel } from '@/api/user'
import { userLogin } from '@/api/user'

const title: string = import.meta.env.VITE_APP_TITLE

const router = useRouter()
const route = useRoute()
const query = route.query

const loginInfo = ref<UserLoginSendModel>({
  phone: '15886357069',
  password: '123456',
  captcha: 'asdf',
})

onMounted(async () => {
  getcaptcha()
})

// 获取图形验证码
const captchaSVG = ref<string>('')
async function getcaptcha() {
  const { code, data } = await getCaptcha()
  if (code === 0)
    captchaSVG.value = data
}

// 获取本地账号缓存
const localLoginInfo = getLocal('loginInfo') as UserLoginSendModel
if (localLoginInfo) {
  loginInfo.value.phone = localLoginInfo.phone || ''
  loginInfo.value.password = localLoginInfo.password || ''
}

// 登录
const loging = ref<boolean>(false)
const isRemember = useStorage('isRemember', false)
async function handleLogin() {
  const { phone, password, captcha } = loginInfo.value
  if (!phone || !password) {
    window.$message?.warning('请输入用户名和密码')
    return
  }
  if (!captcha) {
    window.$message?.warning('请输入图形验证码')
    return
  }
  try {
    loging.value = true
    const { code, data: token } = await userLogin({ phone, password: password.toString(), captcha })
    if (code === 0) {
      window.$notification?.success({ title: '登录成功！', duration: 2500 })

      setToken(token)
      if (isRemember.value)
        setLocal('loginInfo', { phone, password })
      else
        removeLocal('loginInfo')

      await addDynamicRoutes()
      if (query.redirect) {
        const path = query.redirect as string
        Reflect.deleteProperty(query, 'redirect')
        router.push({ path, query })
      }
      else {
        router.push('/')
      }
    }
  }
  catch (error) {
    console.error(error)
  }
  loging.value = false
}
</script>

<template>
  <AppPage :show-footer="true" bg-cover :style="{ backgroundImage: `url(${bgImg})` }">
    <div m-auto p-15 f-c-c min-w-345 rounded-10 card-shadow bg-white dark:bg-dark bg-opacity-60>
      <div w-380 hidden md:block px-20 py-35>
        <img src="@/assets/images/login_banner.webp" w-full alt="login_banner">
      </div>

      <div w-320 flex-col px-20 py-35>
        <h5 f-c-c text-24 font-normal color="#6a6a6a">
          <icon-custom-logo mr-30 w-50 h-50 color-primary />{{ title }}
        </h5>
        <div mt-30>
          <n-input
            v-model:value="loginInfo.phone"
            autofocus
            class="text-16 items-center h-50 pl-10"
            placeholder="用户手机号"
            :maxlength="11"
          />
        </div>
        <div mt-30>
          <n-input
            v-model:value="loginInfo.password"
            class="text-16 items-center h-50 pl-10"
            type="password"
            show-password-on="mousedown"
            placeholder="账号密码"
            :maxlength="20"
          />
        </div>

        <div mt-30 inline-flex>
          <n-input
            v-model:value="loginInfo.captcha"
            class="text-16 items-center h-50 pl-10"
            type="text"
            placeholder="图形验证码"
            :maxlength="4"
            @keydown.enter="handleLogin"
            @input="loginInfo.captcha.length === 4 && handleLogin()"
          />
          <div class="captchaSVG h-50 cursor-pointer" @click="getcaptcha" v-html="captchaSVG" />
        </div>

        <div mt-20>
          <n-checkbox :checked="isRemember" label="记住我" :on-update:checked="(val:boolean) => (isRemember = val)" />
        </div>

        <div mt-20>
          <n-button w-full h-50 rounded-5 text-16 type="primary" :loading="loging" @click="handleLogin">
            登录
          </n-button>
        </div>
      </div>
    </div>
  </AppPage>
</template>

<style lang="scss" scoped>
:deep(.captchaSVG) {
  svg{
    height: 50px;
    width: fit-content;
  }
}
</style>

